import express from 'express';
import fetch from 'node-fetch';
import crypto from 'crypto';
import cors from 'cors'; // 添加cors中间件

const app = express();
const port = 3000;

app.use(cors()); // 使用cors中间件
app.use(express.json());

app.post('/translate', async (req, res) => {
    const { text } = req.body;
    const url = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
    const appid = process.env.BAIDU_APP_ID || '20240705002092238'; // 替换为你的 APP ID
    const secretKey = process.env.BAIDU_SECRET_KEY || 'C0hl_r5oKcgUB4jILP8G'; // 替换为你的密钥
    const salt = Date.now();
    const signStr = appid + text + salt + secretKey;
    const sign = crypto.createHash('md5').update(signStr).digest('hex');

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                q: text,
                from: 'zh',
                to: 'en',
                appid: appid,
                salt: salt,
                sign: sign
            })
        });
        const data = await response.json();
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: 'Translation failed' });
    }
});

app.listen(port, () => {
    console.log(`Proxy server running at http://localhost:${port}`);
});